//
//  FilmModelViewController.m
//  MoreFunTV
//
//  Created by admin on 14-10-23.
//  Copyright (c) 2014年 admin. All rights reserved.
//

#import "FilmModelViewController.h"

@interface FilmModelViewController ()

@end

@implementation FilmModelViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;

    
    //标题自定义
    [self customNav];
    
    //网页视图添加
    [self addWeb];
    
    //下边栏自定义
    [self customToolBar];
}

//标题自定义
-(void)customNav
{
    UIView *viewDiBu = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    viewDiBu.backgroundColor = [UIColor colorWithWhite:0.280 alpha:1.000];
    [viewDiBu setUserInteractionEnabled:YES];
    [self.view addSubview:viewDiBu];
    
    //网页模式按钮
    UIButton *btnFilm = [[UIButton alloc]initWithFrame:CGRectMake(15, 11+20, 65, 22)];
    [btnFilm setTitle:MyLocalizedString(@"yingshi") forState:UIControlStateNormal];
    btnFilm.titleLabel.font = [UIFont systemFontOfSize:14.50f];
    [btnFilm setBackgroundImage:[UIImage imageNamed:@"webView1.png"] forState:UIControlStateNormal];
    [btnFilm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnFilm addTarget:self action:@selector(clickFilm) forControlEvents:UIControlEventTouchUpInside];
    [viewDiBu addSubview:btnFilm];
    
    //TiTle自定义
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 20, 100, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:19.0f];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = MyLocalizedString(@"MoreFunTV");
    [viewDiBu addSubview:titleLabel];
    
    //刷新按钮
    UIButton *btnRefresh = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth-15-40, 20, 40, 44)];
    [btnRefresh setTitle:MyLocalizedString(@"Refresh") forState:UIControlStateNormal];
    btnRefresh.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    [btnRefresh setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnRefresh addTarget:self action:@selector(clickRefresh) forControlEvents:UIControlEventTouchUpInside];
    [viewDiBu addSubview:btnRefresh];
}

//网页视图添加
-(void)addWeb
{
    UIView *viewA = [[UIView alloc]init];
    [self.view addSubview:viewA];
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, 44)];
    searchBar.placeholder = MyLocalizedString(@"input");
    searchBar.tintColor = [UIColor colorWithWhite:0.365 alpha:1.000];
    searchBar.delegate = self;
    [self.view addSubview:searchBar];
    
    self.webView = [[UIWebView alloc] init];
    self.webView.frame = CGRectMake(0, 64+44, 320, kScreenHeight-64-48-44);
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.delegate = self;
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://182.92.182.60/media/nav.html"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
    [self.webView loadRequest:request];
    [self.webView setUserInteractionEnabled:YES];
    [(UIScrollView *)[[self.webView subviews] objectAtIndex:0]setBounces:NO];//禁止webview越界滑动
    [self.view addSubview:self.webView];
}

//下边栏自定义
-(void)customToolBar
{
    //背景view
    UIView *viewBg = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight-48, kScreenWidth, 48)];
    viewBg.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewBg];
    
    UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    viewLine.backgroundColor = [UIColor colorWithWhite:0.784 alpha:1.000];
    [viewBg addSubview:viewLine];
    
    //返回前一页
    //    self.btnBack = [[UIButton alloc]init];
    //    self.btnBack.adjustsImageWhenHighlighted = NO;//取出点击效果
    self.btnBack = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.btnBack.frame = CGRectMake(0, 0, kScreenWidth/4, 48);
    [self.btnBack setImage:[UIImage imageNamed:@"back2.png"] forState:UIControlStateNormal];
    [self.btnBack addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:self.btnBack];
    
    //进入下一页
    //    self.btnNext = [[UIButton alloc]init];
    //    self.btnNext.adjustsImageWhenHighlighted = NO;//取出点击效果
    self.btnNext = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.btnNext.frame = CGRectMake(kScreenWidth/4, 0, kScreenWidth/4, 48);
    [self.btnNext setImage:[UIImage imageNamed:@"next2.png"] forState:UIControlStateNormal];
    [self.btnNext addTarget:self action:@selector(clickNext) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:self.btnNext];
    
    //回到主页
    //    self.btnHome = [[UIButton alloc]init];
    //    self.btnHome.adjustsImageWhenHighlighted = NO;//取出点击效果
    self.btnHome = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.btnHome.frame = CGRectMake(kScreenWidth/4*2, 0, kScreenWidth/4, 48);
    [self.btnHome setImage:[UIImage imageNamed:@"home2.png"] forState:UIControlStateNormal];
    [self.btnHome addTarget:self action:@selector(clickHome) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:self.btnHome];
    
    //收藏
    //    UIButton *btnCollect = [[UIButton alloc]init];
    //    btnCollect.adjustsImageWhenHighlighted = NO;//取出点击效果
    UIButton *btnCollect = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCollect.frame = CGRectMake(kScreenWidth/4*3, 0, kScreenWidth/4, 48);
    [btnCollect setImage:[UIImage imageNamed:@"collect2.png"] forState:UIControlStateNormal];
    [btnCollect addTarget:self action:@selector(clickCollect) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:btnCollect];
    
}

//光标进入搜索框
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //进入编辑时显示取消按钮
//    searchBar.showsCancelButton = YES;//取消按钮
    searchBar.placeholder = @"";
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    searchBar.text = _strTxt;
}

//搜索时
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    _strTextSearch = searchBar.text;
    NSString *strSearch = @"http://";
    NSString *strUrl = @"";
    if ([searchBar.text rangeOfString:strSearch options:NSCaseInsensitiveSearch].length > 0) {
        strUrl = searchBar.text;
    }
    else{
        strUrl = [NSString stringWithFormat:@"%@%@",strSearch,searchBar.text];
    }
    
    NSError *error;
    NSString *regulaStr = @"^(http)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.[a-zA-Z]{2,4})(\\:[0-9]+)?(/[^/][a-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$\\=~_\\-@]*)*$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:strUrl options:0 range:NSMakeRange(0, [strUrl length])];

    if (arrayOfAllMatches.count == 0) {
        _strURL = [NSString stringWithFormat:@"http://www.soku.com/v?keyword=%@",searchBar.text];
        _strURL = [_strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    else{
        for (NSTextCheckingResult *match in arrayOfAllMatches){
            _strURL = [strUrl substringWithRange:match.range];
        }
    }
    //点击键盘右下角Search按钮时调用
    [searchBar resignFirstResponder];
    [self.webView stopLoading];
    NSURLRequest *requestURL = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:_strURL]];
    [self.webView loadRequest:requestURL];
    [self refreshButtonsState];
}

//结束编辑
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
//    searchBar.showsCancelButton = NO;
    _strTxt = searchBar.text;
    if (searchBar.text.length == 0) {
        searchBar.placeholder = @"输入网址或关键字                                      ";
    }
}

////点击搜索框上的 取消按钮时 调用
//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
//{
//    //光标失去焦点  收起键盘
//    [searchBar resignFirstResponder];
//    _strTxt = @"";
//    searchBar.text = @"";
//    searchBar.placeholder = @"输入网址或关键字                                      ";
//    searchBar.showsCancelButton = NO;
//}

//影视模式按钮
-(void)clickFilm
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;
}

//刷新按钮
-(void)clickRefresh
{
    [self.webView reload];
    [self refreshButtonsState];
}

//返回前一页
-(void)clickBack
{
    [self.webView goBack];
    [self refreshButtonsState];
}

//前往下一页
-(void)clickNext
{
    [self.webView goForward];
    [self refreshButtonsState];
}

//回到主页
-(void)clickHome
{
    [self.webView stopLoading];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://182.92.182.60/media/nav.html"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
    [self.webView loadRequest:request];
    [self refreshButtonsState];
}

//收藏
-(void)clickCollect
{
    NSString *currentURL = [self.webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSString *strTitle = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    BookMarksViewController *bookMark = [[BookMarksViewController alloc]initWithTitle:strTitle strURL:currentURL];
    [self presentViewController:bookMark animated:YES completion:^{
    }];
}

/*网页开始加载*/
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [Loading showLoadingWithView:self.view];
    [self refreshButtonsState];
}

/*网页结束加载*/
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [Loading hiddonLoadingWithView:self.view];
    [self refreshButtonsState];
    
    //获取网页的title和网址
    NSString *currentURL = [self.webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSString *strTitle = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    if ([set.strHistoryFlag isEqual:@"YES"]) {
        HistoryInfo *lastHistory = [DBDaoHelper selectLastWebHistory];
        if (![strTitle isEqual:@"酷站导航"] && !([strTitle isEqual:lastHistory.strTitle]&&[currentURL isEqual:lastHistory.strUrl])) {
            HistoryInfo *history = [[HistoryInfo alloc]init];
            history.strTitle =strTitle;
            history.strUrl =currentURL;
            //将历史记录存入数据库
            [DBDaoHelper insertWebHistory:history];
        }
    }
}

/*加载失败*/
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [Loading hiddonLoadingWithView:self.view];
//    NSLog(@"1-----------NSError======%@",error);
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:@"您输入的网址有误，请重新输入！" delegate:nil cancelButtonTitle:MyLocalizedString(@"sure") otherButtonTitles:nil];
//    [alert show];
}

//前进与后退按钮状态监测
- (void)refreshButtonsState
{
    //update the state for the back button
    if (self.webView.canGoBack){
        [self.btnBack setEnabled:YES];
    }
    else{
        [self.btnBack setEnabled:NO];
    }
    
    if (self.webView.canGoForward){
        [self.btnNext setEnabled:YES];
    }
    else{
        [self.btnNext setEnabled:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
